// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message, Upload, Icon } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Home.css'
import R from 'ramda'
// import Tags from 'components/Tags'
const Dragger = Upload.Dragger
import { connect } from 'react-redux'
type Props = {
  userId: string,
  form: Object,
  history: Object,
  data: Object,
  handleCancel: Function,
  addPart: Function
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  fileList: Array<Object>
}
class PartAdd extends React.Component {
  props: Props
  state: States
  changeFile1: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      fileList: []
    }
    this.changeFile1 = this.changeFile1.bind(this)
  }

  componentDidMount () {
  }
  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    const { data } = this.props
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      const values = {
        ...Object.assign({}, fieldsValue, { }),
        'parentId': data.id,
        'produceDate': fieldsValue.produceDate
          ? fieldsValue['produceDate'].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : ''
      }
      values.fileList = values.fileUrl ? values.fileUrl.fileList : []
      this.props.addPart(values)
      this.props.handleCancel() // 关闭弹层
    })
  }
  changeFile1 (info) {
    console.log(info)
    let fileList = info.fileList
    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-10)
    // 2. read from response and show file link
    fileList = fileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.result.url
        file.name = file.name
      }
      return file
    })
    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter((file) => {
      const status = info.file.status
      if (status === 'done') {
        return file.response.status === 'success'
      }
      return true
    })
    console.log(fileList)
    this.setState({ fileList: fileList })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const token = localStorage.getItem('asset_token')

    const props1 = {
      name: 'file',
      multiple: true,
      showUploadList: true,
      headers:{ 'X-Auth':token },
      action: `${__SERVICE_API__}static/statics`,
      onChange: this.changeFile1
    }
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='部件编号' hasFeedback>
            {getFieldDecorator('deviceNo', {
              rules: [
                { required: true, message: '请填写部件编号', whitespace: true }
              ]
            })(
              <Input placeholder='请填写部件编号' ref={(e) => {
                document.querySelector('#deviceNo').focus()
              }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='名字' hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请填写名字', whitespace: true }
              ]
            })(
              <Input placeholder='请填写名字' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='制造商' hasFeedback>
            {getFieldDecorator('certificateNo', {})(
              <Input placeholder='请填写制造商名称' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='生产日期'>
            {getFieldDecorator('produceDate')(
              <DatePicker style={{ width: 260 }} placeholder='请选择生产日期' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='文件'>
            {
              getFieldDecorator('fileUrl', {})(
                <Dragger {...props1}>
                  <p className='ant-upload-drag-icon'>
                    <Icon type='inbox' />
                  </p>
                  <p className='ant-upload-text'>点击或者拖拽文件到该区域</p>
                  <p className='ant-upload-hint'>支持单个或批量上传</p>
                </Dragger>
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'
              >保存</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.props.handleCancel}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(PartAdd))
